﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Hospitalbeds;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Hospitalbeds
{
    /// <summary>
    /// 获取所有病房处理器
    /// </summary>
    public class GetHospitalroomsHandler : IRequestHandler<GetHospitalroomsCommand, APIResult<List<HospitalRoomDto>>>
    {
        private readonly IBaseRepository<HospitalRoomModel> hospitalRoomRepository;
        private readonly IBaseRepository<DepartmentModel> departmentRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetHospitalroomsHandler> logger;

        public GetHospitalroomsHandler(
            IBaseRepository<HospitalRoomModel> hospitalRoomRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            IMapper mapper,
            ILogger<GetHospitalroomsHandler> logger)
        {
            this.hospitalRoomRepository = hospitalRoomRepository;
            this.departmentRepository = departmentRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 获取所有病房信息（与科室表连查）
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<HospitalRoomDto>>> Handle(GetHospitalroomsCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<HospitalRoomDto>> res = new APIResult<List<HospitalRoomDto>>();

            try
            {
                // 获取所有未删除的病房和科室
                var allHospitalRooms = hospitalRoomRepository.GetALL().Where(x => x.IsDeleted == false).ToList();
                var allDepartments = departmentRepository.GetALL().Where(x => x.IsDeleted == false).ToList();

                logger.LogInformation($"数据库中总共有{allHospitalRooms.Count}个未删除的病房，{allDepartments.Count}个科室");

                // 使用LINQ进行两表联查
                var query = from room in allHospitalRooms
                           join dept in allDepartments on room.Department_id equals dept.Id
                           select new { Room = room, Department = dept };

                var results = query.ToList();
                logger.LogInformation($"病房和科室联查找到{results.Count}条记录");

                // 转换为DTO并填充科室名称
                var hospitalRoomDtos = new List<HospitalRoomDto>();
                foreach (var result in results)
                {
                    var roomDto = mapper.Map<HospitalRoomDto>(result.Room);
                    roomDto.DepartmentName = result.Department.DepartmentName;
                    hospitalRoomDtos.Add(roomDto);
                    
                    logger.LogInformation($"病房ID: {result.Room.Id}, 病房编码: {result.Room.HospitalRoomCode}, 科室ID: {result.Room.Department_id}, 科室名称: {result.Department.DepartmentName}");
                }

                res.Data = hospitalRoomDtos;
                res.Code = APIEnums.Success;
                res.Msg = "查询成功";
                logger.LogInformation($"查询病房成功，共查询到{hospitalRoomDtos.Count}个病房");
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "查询病房失败";
                logger.LogError(ex, "查询病房时发生异常");
            }

            return Task.FromResult(res);
        }
    }
}
